import { Component, OnInit, ViewChild } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Router, ActivatedRoute } from "@angular/router";
import { CuValidators } from 'ng-zorro-iop';
import 'codemirror/mode/yaml/yaml.js';
import { UploadParam, Region, EnvVariable } from "./../../shared-component/class/instance";
import {FormBuilder, FormControl, FormGroup, ValidatorFn, Validators} from "@angular/forms";
import { FcsService } from "../../service/fcs.service";
import { NzMessageService } from "ng-zorro-antd";
import { NzModalRef, NziModalService } from 'ng-zorro-iop';
// import { RuntimeComponent } from './runtime/runtime.component';
import { FormValidator } from '../formvalidator';
import { I } from '@angular/cdk/keycodes';

@Component({
  selector: 'app-layer-update',
  templateUrl: './layer-update.component.html',
  styleUrls: ['./layer-update.component.css']
})
export class LayerUpdateComponent implements OnInit {
  @ViewChild('layerFormComponent', {static: true}) layerFormComponent;
  @ViewChild('functionFormComponent', { static: true }) functionFormComponent;
  layerForm: FormGroup;

  isCodeLoading: boolean = false; //是否在加载在线代码
  uploadType = 'upload'; //upload
  localCode = null;

  uploadFiles = []; //上传的文件
  uploadTypeList = [
    // { label: '在线编辑', value: 'online' },
    { label: '本地上传', value: 'upload' },
    { label: '从 OSS 上传', value: 'oss' }
  ];
  runtime: string = "python3.6"; //运行环境
  RuntimeCustomContainer = "custom-container"
  runtimeList = [
    { key: 'python2.7', value: 'Python 2.7', code: false, icon: "#icon-runtimepython" },
    { key: 'python3.6', value: 'Python 3.6', code: false, icon: "#icon-runtimepython" },
    { key: 'nodejs10.22', value: 'Nodejs 10.22', code: false, icon: "#icon-runtimeNodejs" },
    { key: 'nodejs12.18', value: 'Nodejs 12.18', code: false, icon: "#icon-runtimeNodejs" },
    { key: 'golang1', value: 'Golang 1', code: false, icon: "#icon-runtimego" },
    { key: 'java8', value: 'Java 8', code: false, icon: "#icon-runtimejava" },
    { key: 'custom-container', value: '自定义镜像', code: false, icon: "#icon-runtimeDocker" },
  ]; // code为是否获取到了code
 
  fileMaxSize = 50;
  isJarFile: boolean = true;
  isZipFile: boolean = true;
  exceedFileMaxSize: boolean = false;
  focusFileInput: boolean = false;
 

  zipPlace: string = '选择上传文件，格式为 zip';
  jarPlace: string = '选择上传文件，格式为 zip / jar';
  filePlaceholder: string = this.zipPlace;

	visible: boolean;
  ossBucket: string;
  ossFile: string;
  ossBucketList = [];
  isLoadingBucket: boolean = false;

  regionList = [];
  tagList = [];
  currentRegion: Region = {
    regionCode: '',
    regionName: ''
  };
  regionCode: string = ''; //当前选中的region
  tagListTit=[];
  layerName = "";
  layerId = "";
  isTagList = true;


  // isLayerName: boolean = true;
  // layname = "";

  constructor(
    private http: HttpClient, 
    private fb: FormBuilder,
    private router: Router,
    private fcsService: FcsService,
    private msgService: NzMessageService,
    private activatedRoute: ActivatedRoute,
    private modalService: NziModalService
    ) {
    this.layerForm = this.fb.group({
    //   layerName: [null, [Validators.required,FormValidator.lname]],
      description: [null,[Validators.maxLength(500)]],
      upload: [this.uploadType],
      fileName: ['', [Validators.required, this.fileNameValidator]],
      ossBucket: [''],
      ossFile: [''],
      compatibleRuntimes: [this.tagListTit]
    });
  }
  

    ngOnInit() {
     this. getRegion();
     
     this.layerId = this.activatedRoute.snapshot.queryParams['layerId'];
     this.getLayerName();
    }

    getLayerName(){
        this.fcsService.getLayerDetail(this.layerId).subscribe(res => {
            this.layerName = res.layerName
            // console.log(res)
        })
    }


    getRegion() {
      let regionList = JSON.parse(sessionStorage.getItem('region-FCS'));
      regionList = regionList.map(item => {
        return {
          regionCode: item["regionId"],
          regionName: item["regionName"],
          cloudManageRegion: item["cloudManageRegion"]
        }
      });

      regionList.forEach(i => {
        // if(i.cloudManageRegion){
          this.currentRegion = {
            regionCode: i.regionCode,
            regionName: i.regionName,
          };
        // }
      });
      // console.log(this.currentRegion)
    }

    runtimeChange(runtime) {
      this.runtime = runtime.key;
      // console.log(this.tagListTit.indexOf(runtime.key))
      if (this.tagListTit.indexOf(runtime.key) ==-1) {
        this.tagListTit.push(runtime.key)
      }else{
        this.tagListTit.splice(this.tagListTit.indexOf(runtime.key),1)
      }
      
      // console.log(this.tagListTit)
      // this.setControlVal("runtime", this.runtime);
      
      // if (this.runtime != this.RuntimeCustomContainer) {
      //   this.setUploadShow();
      //   this.getCode(this.runtime);
      // }
      // this.zone.run(() => { });
    }
  
    setShadow(value) {
      if (this.tagListTit.indexOf(value) !==-1) {
        const styles = {
          'box-shadow': 'rgba(81, 112, 255, 0.4) 0px 0px 10px 0px',
          'border': '1px solid #40a9ff'
        };
        return styles;
      }
    }
    
    // runtime() : void{
      
    //     const modal = this.modalService.create({
    //       nzTitle: '添加运行环境',
    //       nzContent: RuntimeComponent,
    //       nzComponentParams: {
    //         // componentInstance: data
    //       },
    //       nzWidth: "7rem",
    //       nzOnOk: (componentInstance) => {
    //         this.tagList = componentInstance.rightbox;
    //         for(let i=0;i<this.tagList.length;i++ ){
    //           this.tagListTit.push(this.tagList[i].value);
    //          }
    //       }
    //     });
     
    
    // }

    fileSizeValidator() {
      if (this.uploadFiles.length > 0) { //计算上传文件的大小，每个文件Bite
        let file_size = this.uploadFiles[0].size / 1024 / 1024;
        if (file_size > this.fileMaxSize) {
          this.exceedFileMaxSize = true;
        } else {
          this.exceedFileMaxSize = false;
        }
      }
    }

    uploadTypeChange(event) {

      if(this.uploadType === 'oss'){
        this.getOssBuckets();
        this.layerForm.get('ossBucket').setValidators(Validators.required);
        this.layerForm.get('ossFile').setValidators([Validators.required, this.ossFileValidator]);
        this.layerForm.get('fileName').setValidators(null);
      }else{
        this.layerForm.get('fileName').setValidators([Validators.required,this.fileNameValidator]);
        this.layerForm.get('ossBucket').setValidators(null);
        this.layerForm.get('ossFile').setValidators(null)
      }

    //  if (this.uploadType === 'upload' && this.localCode) {
    //   } else if (this.uploadType === 'oss') {
    //     //获取ossBucket
    //     this.getOssBuckets();
    //   }
    }

    getOssBuckets() {
      this.isLoadingBucket = true;
      this.fcsService.getOssBucketList(1, 10000).subscribe(res => {
        if (res && res['data']) {
          let resBuckets = res.data;
          if (this.ossBucketList.length <= 0) {
            resBuckets.forEach(item => {
              this.ossBucketList.push({ label: item.bucketName, value: item.bucketName });
            })
          }
        }
        this.isLoadingBucket = false;
      }, err => {
        this.isLoadingBucket = false;
        this.msgService.error('网络错误');
      })
    }

    // layerValidator(e:FormControl){
    //   let str = e.value;
    //   let reg=/^[a-z0-9\u4e00-\u9fa5][-a-z0-9\u4e00-\u9fa5\.\_]{0,127}[a-z0-9\u4e00-\u9fa5]$/;
    //   if(reg.test(str)){
    //   //  console.log("tongg ");
    //     // return {islayername : true};
    //     // console.log(isLayerName)
    //     // this.isLayerName = true;
    //   }else{
    //     // console.log("no");
    //     // this.isLayerName = false;
       
        
    //   }
    // }


    // layernamechange(){
    //   const reg = /^[a-z0-9\u4e00-\u9fa5][-a-z0-9\u4e00-\u9fa5\.\_]{0,127}[a-z0-9\u4e00-\u9fa5]$/;
		// 	const matchFlag = reg.test(this.layname);
    //   console.log(this.layname)
    //   if(matchFlag){
    //     console.log("tongg ");
    //      // return {islayername : true};
    //      // console.log(isLayerName)
    //      this.isLayerName = true;
    //    }else{
    //      console.log("no");
    //      this.isLayerName = false;
        
         
    //    }
    // }

    fileNameValidator(control: FormControl): any {
      let name: string = control.value;
      let pattern = new RegExp('^[^\\\\\/\:\*\?\"\<\>\|]+[\s]*[^\\\\\/\:\*\?\"\<\>\|]*\.zip$');
      if (!pattern.test(name)) {
        return { fileName: true };
      }
      return null;
    }

    fileNameValidator2(fileName) {
      let name: string = fileName;
      let pattern = new RegExp('^[^\\\\\/\:\*\?\"\<\>\|]+[\s]*[^\\\\\/\:\*\?\"\<\>\|]*\.zip$');
      if (pattern.test(name)) {
        this.isZipFile = true;
      } else {
        this.isZipFile = false;
      }
      let pattern2 = new RegExp('^[^\\\\\/\:\*\?\"\<\>\|]+[\s]*[^\\\\\/\:\*\?\"\<\>\|]*\.jar$');
      if (pattern2.test(name)) {
        this.isJarFile = true;
      } else {
        this.isJarFile = false;
      }
    }

    getInvalidMessage(name) {
      let validResult = this.functionFormComponent ? this.functionFormComponent.getInvalidMessage(name) : null;
      return validResult;
    }
    
    ossFileValidator(control: FormControl): any {
      let oss_file: string = control.value;
      let pattern = new RegExp('^/{1}(?:([^\\\\\/\:\*\?\"\<\>\|]+[\s]*[^\\\\\/\:\*\?\"\<\>\|]*/))*[^\\\\\/\:\*\?\"\<\>\|]+[\s]*[^\\\\\/\:\*\?\"\<\>\|]*\.zip$');
      if (!pattern.test(oss_file)) {
        return { ossFile: true };
      }
      return null;
    }

    focusFileName() {
      this.focusFileInput = true;
    }
  
    blurFileName() {
      this.focusFileInput = false;
    }
    setControlVal(formControlName: string, val: string | boolean) {
      this.layerForm.get(formControlName).patchValue(val);
    }
    onChange(e) {
      var obj = e.srcElement ? e.srcElement : e.target;
      if (obj.files.length == 0) {
        return false;
      }
      const file = obj.files[0]; // 获取从上传本地文件转换的数据
      this.setControlVal('fileName', file.name);
      this.fileNameValidator2(file.name);
      // if (this.runtime.indexOf('java8') < 0) {
      //   if (!this.isZipFile) {
      //     return;
      //   }
      // } else if (this.runtime.indexOf('java8') > 0) {
      //   if (!this.isZipFile && !this.isJarFile) {
      //     return;
      //   }
      // }
      this.uploadFiles = obj.files;
      this.fileSizeValidator();
      if (this.exceedFileMaxSize) {
        return;
      }
      var size = file.size / 1024 / 1024;
      if (size > this.fileMaxSize) {
        this.msgService.error(`附件大小不能大于${this.fileMaxSize} +M！`);
        obj.value = "";
        return false;
      }
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = (e) => {
        this.localCode = e.target['result']; // 获取文件装换后的Base64位文件
        this.localCode = this.localCode.split('base64,')[1];
      };
    }

    ossFileChange(event) {
      this.ossFile = event;
    }
  
    getRuntimeList(e){
      
      for(let i=0;i<this.tagList.length;i++ ){
        if (this.tagList[i].title === e) {
          this.tagList.splice(i, 1);
          // console.log(this.tagList)
      }
    }
  }
  
  /**
     * 返回上一页
     */
  goback() {
    window.history.back();
  }

  


 
  // 表单提交
  submit() {
	
		for (const i in this.layerForm.controls) {
			this.layerForm.controls[i].markAsDirty();
			this.layerForm.controls[i].updateValueAndValidity();
		}

    
    if((this.tagListTit.length > 5) || (this.tagListTit.length == 0)){
      this.isTagList = false;
      return false;
    }else{
      this.isTagList = true;
    }

		if (!this.layerForm.valid) {
      // this.msgService.error('请检查表单信息！');
			return false;
		}
    
    
    this.visible = true;
    // if (!this.layerFormComponent.validForm()) return;
    let value = this.layerFormComponent.getFormData();
    
   
		const params = {
			runtimes:value.compatibleRuntimes,
			description:value.description
		}
    this.fcsService.getLayerVersion(this.layerId,params).subscribe(res => {
        // console.log(res)
			if(res['layerId']){
				let data = {
                    code: this.localCode
                 };
			
        if(this.uploadType === 'oss'){
            data['object'] = value.ossFile;
            data['bucket'] = value.ossBucket;
        };
				this.fcsService.uploadCode(data,res['layerId']).subscribe(res => {
                    this.msgService.success('层版本创建成功');

                    const layerDetailUrl = '/layer/detail/' + this.layerId ;
                    // groupDisplayName
                    this.router.navigate([layerDetailUrl],
                      {
                          queryParams:{layerId:this.layerId,regionCode:this.currentRegion.regionCode,regionName:this.currentRegion.regionName
                        }
                      });


				})
			}
     
      
       
    }, error => {}
		)

  }

  cancel () {
    this.visible = false;
    window.history.back();
  }
   


}